package classictravellersalesman;

import java.util.HashSet;

import stochastic.Solution;

public class ThreadSolution implements Runnable {
	public Solution sol;
	private double t;
	private int num;
	private int ID;
	HashSet<Integer> successThreads;
	HashSet<Integer> endThreads;
	
	public ThreadSolution(Solution s, int numPerturb, HashSet<Integer> st, HashSet<Integer> et, double t, int ID) {
		this.sol = s;
		num = numPerturb;
		successThreads = st;
		endThreads = et;
		this.t = t;
		this.ID = ID;
	}

	@Override
	public void run() {
		for(int z=0;z<num;++z) {
			Solution candidat = sol.perturb();
			if(candidat.getCost() <= sol.getCost() ) {
				sol = candidat;
				synchronized (successThreads) {
					successThreads.add(ID);
				}	
				
			}
			else if(candidat.getCost() > sol.getCost()) {
				double delta = candidat.getCost() - sol.getCost();
				if(Math.random() < Math.exp(-delta/t)) {
					sol = candidat;
					synchronized (successThreads) {
						successThreads.add(ID);
					}		 
				}
			}
		}
		
		synchronized (endThreads) {
			endThreads.add(ID);
		}
		
	}
}
